<?php
namespace App\Service\Admin\Qudao;

use Illuminate\Support\Facades\DB;

class GoodsService extends BaseService
{
    //商品

    /**
     * 列表
     * @param array $pages【start，limit】
     */
    public function getList($pages,$pas)
    {
        $start = ($pages['start'] - 1) * $pages['limit'];
        $db = $this->db2Conn($this->dbQdGoods)->where('del', 0);
        if ($pas['gno']) {
            $db = $db->where('gno', 'like', '%'.$pas['gno'].'%');
        }
        if ($pas['title']) {
            $db = $db->where('title', 'like', '%'.$pas['title'].'%');
        }

        if (!empty($pas['cate_id'])) {
            $db->where('cate_id', $pas['cate_id']);
        }

        if ($pas['sale_min']) {
            $db = $db->where('sale', '>=',$pas['sale_min']);
        }

        if ($pas['sale_max']) {
            $db = $db->where('sale', '<=',$pas['sale_max']);
        }

        if ($pas['is_shelf']) {
            if($pas['is_shelf'] == 1){
                $db = $db->where('is_shelf', $pas['is_shelf']);
            }else{
                $db = $db->where('is_shelf',0);
            }
        }
        if ($pas['isnew']) {
            if($pas['isnew'] == 1){
                $db = $db->where('isnew', $pas['isnew']);
            }else{
                $db = $db->where('isnew',0);
            }
        }
        $total = $db->count();
        $res = $db->skip($start)->take($pages['limit'])
            ->orderBy('id', 'desc')
            ->get();
        if (!count($res)) {
            return array('code' => -2, 'msg' => '没有商品');
        }
        $arys = [];
        foreach ($res as $v ) {
            $v = (array) $v;
            $cateOne = (array) $this->db2Conn($this->dbQdGcate)
                ->where('del', 0)
                ->where('id', $v['cate_id'])
                ->first();
            $cate_name = !empty($cateOne) ? $cateOne['title'] : '';
            if (file_exists($v['bigimg'])) {
                $imgPrefix = env('DOMAIN') . '/';
            } else {
                $imgPrefix = env('FC_DOMAIN') . '/';
            }
            //下单的统计
            $sale = $this->dbwbConn($this->dbQdOsku)->where('gid', $v['id'])->sum('num');
            $this->dbwbConn($this->dbQdGoods)->where('id', $v['id'])->update(['sale' => $sale]);
            $arys[] = [
                'id' => $v['id'],
                'gno' => $v['gno'],
                'title' => $v['title'],
                'imgPrefix' =>  $imgPrefix,
                'imgLink' =>  $v['bigimg'],
                'cate_id' => $v['cate_id'],
                'cate_name' => $cate_name,
                //'sale' => $v['sale'],
                'isnew' => $v['isnew'],
                'is_in_reason' => $v['is_in_reason'],
                'price_one' => toNumber($v['price_one']),
                'price_two' => toNumber($v['price_two']),
                'sale' => $sale,
                'shelf' => $v['is_shelf'],
            ];
        }
        return array('code' => 0, 'msg' => 'success', 'data' => $arys, 'total' => $total);
    }
    /**
     * 批量上下架
     * @param array ids
     * @param int $status 状态
     */
    public function batchStatus($ids, $status)
    {
        if(empty($ids))
        {
            return array('code' => 0, 'msg' => 'success');
        }
        $up = $this->db2Conn($this->dbQdGoods)
            ->whereIn('id', $ids)
            ->update(['is_shelf' => $status, 'uptime' => toDate()]);
        if (!$up) {
            return array('code' => -2, 'msg' => '修改失败');
        }
        return array('code' => 0, 'msg' => 'success');
    }
    /**
     * 批量删除
     * @param array ids
     */
    public function batchDel($ids)
    {
        if(empty($ids))
        {
            return array('code' => 0, 'msg' => 'success');
        }
        $up = $this->db2Conn($this->dbQdGoods)
            ->whereIn('id', $ids)
            ->update(['del' => 1, 'uptime' => toDate()]);
        if (!$up) {
            return array('code' => -2, 'msg' => '刪除失败');
        }
        return array('code' => 0, 'msg' => 'success');
    }

    /**
     * 列表
     */
    public function getGlist()
    {
        $db = $this->db2Conn($this->dbQdGoods)->where('del', 0);
        $total = $db->count();
        $res = $db->get();
        if (!count($res)) {
            return array('code' => -2, 'msg' => '没有商品');
        }
        $arys = [];
        foreach ($res as $v ) {
            $v = (array) $v;
            $cateOne = (array) $this->db2Conn($this->dbQdGcate)
                ->where('del', 0)
                ->where('id', $v['cate_id'])
                ->first();
            $cate_name = !empty($cateOne) ? $cateOne['title'] : '';
            if (file_exists($v['bigimg'])) {
                $imgPrefix = env('DOMAIN') . '/';
            } else {
                $imgPrefix = env('FC_DOMAIN') . '/';
            }
            $arys[] = [
                'id' => $v['id'],
                'gno' => $v['gno'],
                'title' => $v['title'],
                'img' =>  $imgPrefix.$v['bigimg'],
                'cate_name' => $cate_name,
                'sale' => $v['sale'],
                'isnew' => $v['isnew'],
                'is_in_reason' => $v['is_in_reason'],
                'price_one' => toNumber($v['price_one']),
                'price_two' => toNumber($v['price_two']),
            ];
        }
        return array('code' => 0, 'msg' => 'success', 'data' => $arys);
    }

    /**
     * 分类选项
     */
    public function getCateList()
    {
        $arys[] = [ 'id' => 0, 'title' => '-选择分类-' ];
        $res = $this->db2Conn($this->dbQdGcate)->where('del', 0)->get();
        if (count($res)) {
            foreach ($res as $v) {
                $v = (array) $v;
                $arys[] = [
                    'id' => $v['id'],
                    'title' => $v['title'],
                ];
            }
        }
        return array('code' => 0, 'msg' => 'success', 'data' => $arys);
    }

    /**
     * 一个
     * @param int $id 商品ID
     */
    public function getOne($id)
    {
        $res = (array) $this->db2Conn($this->dbQdGoods)
            ->where('del', 0)
            ->where('id', $id)
            ->first();
        if (empty($res)) {
            return array('code' => -2, 'msg' => '没有商品');
        }
        //分类
        $cateOne = (array) $this->db2Conn($this->dbQdGcate)
            ->where('del', 0)
            ->where('id', $res['cate_id'])
            ->first();
        $cate_name = !empty($cateOne) ? $cateOne['title'] : '';
        //详情图
        $moreImgs = [];
        $moreImgOnes = $this->db2Conn($this->dbQdGimg)
            ->where('del', 0)
            ->where('gid', $res['id'])
            ->get();
        if (count($moreImgOnes)) {
            foreach ($moreImgOnes as $v) {
                $v = (array) $v;
                $moreImgs[] = [
                    'id' => $v['id'],
                    'imgDomain' => file_exists($v['link']) ? env('DOMAIN') . '/' : env('FC_DOMAIN') . '/',
                    'img' => $v['link'],
                    'w' => $v['width'],
                    'h' => $v['height'],
                ];
            }
        }
        //SKU
        $skuLists = [];
        $skuOnes = $this->db2Conn($this->dbQdGsku)
            ->where('del', 0)
            ->where('gid', $res['id'])
            ->get();
        if (count($skuOnes)) {
            foreach ($skuOnes as $v) {
                $v = (array) $v;
                $skuLists[] = [
                    'id' => $v['id'],
                    'title' => $v['title'],
                    'price' => toNumber($v['price']),
                    'price_line' => toNumber($v['price_line']),
                    'price_one' => toNumber($v['price_one']),
                    'price_two' => toNumber($v['price_two']),
                    'stock' => $v['stock'],
                    'commission_rate' => $v['commission_rate'],
                ];
            }
        }
        $arys = [
            'id' => $res['id'],
            'title' => $res['title'],
            'imgDomain' => file_exists($res['bigimg']) ? env('DOMAIN') . '/' : env('FC_DOMAIN') . '/',
            'img' => $res['bigimg'],
            'cate_id' => $res['cate_id'],
            'cate_name' => $cate_name,
            'sale' => $res['sale'],
            'detail' => $res['detail'] ? htmlspecialchars_decode($res['detail']) : '',
            'isnew' => $res['isnew'],
            'moreImgs' => $moreImgs,
            'skuLists' => $skuLists,
            'is_in_reason' => $res['is_in_reason'],
            'price_one' => toNumber($res['price_one']),
            'price_two' => toNumber($res['price_two']),
        ];
        return array('code' => 0, 'msg' => 'success', 'data' => $arys);
    }

    /**
     * 添加
     * @param array $pas
     * @param array $imgs
     * @param array $skus
     */
    public function addOne($pas, $imgs, $skus)
    {
        //添加商品
        $gData = [
            'title' => $pas['title'],
            'gno' => toGno(),
            'cate_id' => $pas['cate_id'],
            'bigimg' => $pas['bigimg'],
            'detail' => $pas['detail'] ? htmlspecialchars($pas['detail']) : '',
            'isnew' => $pas['isnew'],
            'is_in_reason' => $pas['is_in_reason'],
            'price_one' => $pas['price_one'],
            'price_two' => $pas['price_two'],
            'addtime' => toDate(),
            'uptime' => toDate(),
        ];
        DB::beginTransaction(); //开启事务
        try {
            $gid = $this->db2Conn($this->dbQdGoods)->insertGetId($gData);
            if (!$gid) {
                return $this->toback(-1, '商品error');
            }
            //添加详情图
            foreach ($imgs as $v) {
                $imgData = [
                    'gid' => $gid,
                    'link' => $v['img'],
                    'width' => $v['w'],
                    'height' => $v['h'],
                    'addtime' => toDate(),
                ];
                $imgup = $this->db2Conn($this->dbQdGimg)->insertGetId($imgData);
                if (!$imgup) {
                    return $this->toback(-1, 'img error');
                }
            }
            //添加SKU
            foreach ($skus as $v) {
                $skuData = [
                    'gid' => $gid,
                    'title' => $v['title'],
                    'price' => $v['price'] * 100,
                    'price_line' => $v['price_line'] * 100,
                    'price_one' => $v['price_one'] * 100,
                    'price_two' => $v['price_two'] * 100,
                    'stock' => $v['stock'],
                    'commission_rate' => $v['rate'],
                    'addtime' => toDate(),
                    'uptime' => toDate(),
                ];
                $skuid = $this->db2Conn($this->dbQdGsku)->insertGetId($skuData);
                if (!$skuid) {
                    return $this->toback(-1, 'sku失败');
                }
            }
//            $this->setGprice($gid); //更新商品价格
            DB::commit(); //提交事务
            return $this->toback();
        } catch (\Exception $e) {
            DB::rollBack(); //事务回滚
            echo $e->getMessage();
            return $this->toback(-1, 'error');
        }
    }

//    /**
//     * 更新商品价格（选最小的）
//     * @param int $gid 商品ID
//     */
//    public function setGprice($id)
//    {
//        $skuOne = (array) table($this->dbGsku)->where('gid', $id)
//            ->orderBy('price', 'asc')
//            ->first();
//        $price = empty($skuOne) ? 0 : $skuOne['price'];
//        return DB::table($this->dbGoods)->where('id', $id)->update(['price' => $price]);
//    }

    /**
     * 多图上传
     * @param int $id 商品ID
     * @param string $img
     * @param int $iw
     * @param int $ih
     */
    public function moreUpload($id, $img, $iw, $ih)
    {
        $total = DB::table($this->dbGimg)
            ->where('del', 0)
            ->where('gid', $id)
            ->count();
        if ($total >= 5) {
            return array('code' => -2, 'msg' => '详情最多5张');
        }
        //图片集合
        $this->dbConn($this->dbImg)->insertGetId([
            'link' => $img,
            'width' => $iw,
            'height' => $ih,
            'addtime' => toDate(),
        ]);
        //商品多图
        $this->db2Conn($this->dbQdGimg)->insertGetId([
            'gid' => $id,
            'link' => $img,
            'width' => $iw,
            'height' => $ih,
            'addtime' => toDate(),
        ]);
        return array('code' => 0, 'msg' => 'success');
    }

    /**
     * 多图删除
     * @param int $id 图片ID
     */
    public function moreDel($id)
    {
        $res = (array) $this->db2Conn($this->dbQdGimg)
            ->where('del', 0)
            ->where('id', $id)
            ->first();
        if (empty($res)) {
            return array('code' => -2, 'msg' => '图片不存在');
        }
        //商品多图
        $this->db2Conn($this->dbQdGimg)->where('id', $id)
            ->update([
                'id' => $id,
                'del' => 1,
                'deltime' => toDate(),
            ]);
        return array('code' => 0, 'msg' => 'success');
    }

    /**
     * 修改
     * @param int $id 商品ID
     * @param array $pas
     */
    public function modify($id, $pas)
    {
        $res = (array) $this->db2Conn($this->dbQdGoods)
            ->where('del', 0)
            ->where('id', $id)
            ->first();
        if (empty($res)) {
            return array('code' => -2, 'msg' => '商品不存在');
        }
        //修改商品
        $gData = [
            'title' => $pas['title'],
            'cate_id' => $pas['cate_id'],
            'bigimg' => $pas['bigimg'],
            'detail' => $pas['detail'] ? htmlspecialchars($pas['detail']) : '',
            'isnew' => $pas['isnew'],
            'is_in_reason' => $pas['is_in_reason'],
            'price_one' => $pas['price_one'],
            'price_two' => $pas['price_two'],
            'uptime' => toDate(),
        ];
        $gup = $this->db2Conn($this->dbQdGoods)->where('id', $id)->update($gData);
        if (!$gup) {
            return array('code' => -2, 'msg' => 'error');
        }
//        $this->setGprice($id); //更新商品价格
        return array('code'=>0, 'msg'=>'success');
    }

    /**
     * 删除
     * @param int $id 商品ID
     */
    public function setDel($id)
    {
        $res = (array) $this->db2Conn($this->dbQdGoods)
            ->where('del', 0)
            ->where('id', $id)
            ->first();
        if (empty($res)) {
            return array('code' => -2, 'msg' => '商品不存在');
        }
        $arys = [
            'del' => 1,
            'deltime' => toDate(),
        ];
        $up = $this->db2Conn($this->dbQdGoods)->where('id', $id)->update($arys);
        if (!$up) {
            return array('code' => -2, 'msg' => 'error');
        }
//        //清理购物车对应记录
//        $this->dbConn($this->dbCart)->where('gid', $id)->update(['g_del' => 1]);
        return array('code' => 0, 'msg' => 'success');
    }

    /**
     * 上下架
     * @param int $id
     * @param int $shelf
     */
    public function setShelf($id, $shelf)
    {
        $res = (array) $this->dbwbConn($this->dbQdGoods)->where('id', $id)->first();
        if (empty($res)) {
            return $this->toback(-2, '该商品不存在');
        }
        $this->dbwbConn($this->dbQdGoods)->where('id', $id)->update(['is_shelf' => $shelf]);
        return $this->toback();
    }

    /**
     * SKU添加
     * @param array $pas 商品SKU
     */
    public function skuAdd($pas)
    {
        $arys = [
            'gid' => $pas['gid'],
            'title' => $pas['title'],
            'price' => $pas['price'] * 100,
            'price_line' => $pas['price_line'] * 100,
            'price_one' => $pas['price_one'] * 100,
            'price_two' => $pas['price_two'] * 100,
            'stock' => $pas['stock'],
            'commission_rate' => $pas['rate'],
            'addtime' => toDate(),
            'uptime' => toDate(),
        ];
        $lastid = $this->db2Conn($this->dbQdGsku)->insertGetId($arys);
        if (!$lastid) {
            return array('code' => -2, 'msg' => 'error');
        }
        return array('code' => 0, 'msg' => 'success');
    }

    /**
     * SKU修改
     * @param int $id SKU的ID
     * @param array $pas 商品SKU
     */
    public function skuModify($id, $pas)
    {
        $res = (array) $this->db2Conn($this->dbQdGsku)->where('del', 0)->where('id', $id)->first();
        if (empty($res)) {
            return array('code' => -2, 'msg' => '该SKU不存在');
        }
        $arys = [
            'title' => $pas['title'],
            'price' => $pas['price'] * 100,
            'price_line' => $pas['price_line'] * 100,
            'price_one' => $pas['price_one'] * 100,
            'price_two' => $pas['price_two'] * 100,
            'stock' => $pas['stock'],
            'commission_rate' => $pas['rate'],
            'uptime' => toDate(),
        ];
        $up = $this->db2Conn($this->dbQdGsku)->where('id', $id)->update($arys);
        if (!$up) {
            return array('code' => -2, 'msg' => 'error');
        }
        return array('code' => 0, 'msg' => 'success');
    }

    /**
     * SKU删除
     * @param int $id SKU的ID
     */
    public function skuDel($id)
    {
        $res = (array) $this->db2Conn($this->dbQdGsku)->where('del', 0)->where('id', $id)->first();
        if (empty($res)) {
            return array('code' => -2, 'msg' => '该SKU不存在');
        }
        $arys = [
            'del' => 1,
            'deltime' => toDate(),
        ];
        $up = $this->db2Conn($this->dbQdGsku)->where('id', $id)->update($arys);
        if (!$up) {
            return array('code' => -2, 'msg' => 'error');
        }
        return array('code' => 0, 'msg' => 'success');
    }

    /**
     * SKU列表
     * @param array $pages【start，limit】
     * @param int $gid
     */
    public function skuList($pages, $gid)
    {
        $start = ($pages['start'] - 1) * $pages['limit'];
        $db = $this->dbwbConn($this->dbQdGsku)->where('del', 0)
            ->where('gid', $gid);
        $total = $db->count();
        $res = $db->skip($start)->take($pages['limit'])
            ->orderBy('id', 'desc')
            ->get();
        if (!count($res)) {
            return array('code' => -2, 'msg' => '没有记录');
        }
        $arys = [];
        foreach ($res as $v ) {
            $v = (array) $v;
            $arys[] = [
                'id' => $v['id'],
                'gid' => $v['gid'],
                'title' => $v['title'],
                'price' => toNumber($v['price']),
                'stock' => $v['stock'],
            ];
        }
        return array('code' => 0, 'msg' => 'success', 'data' => $arys, 'total' => $total);
    }

//    /**
//     * 关键词列表
//     */
//    public function getWordList($pages)
//    {
//        $start = ($pages['start'] - 1) * $pages['limit'];
//        $db = DB::table($this->dbGkeyword)->where('del', 0);
//        $total = $db->count();
//        $res = $db->orderBy('id', 'desc')
//            ->skip($start)->take($pages['limit'])
//            ->get();
//        if (!count($res)) {
//            return array('code' => -2, 'msg' => '没有关键词');
//        }
//        $arys = [];
//        foreach ($res as $v) {
//            $v = (array) $v;
//            $uOne = (array) DB::table($this->dbUser)->where('id', $v['uid'])->first();
//            $nick = empty($uOne) ? '-' : $uOne['nickname'];
//            $arys[] = [
//                'id' => $v['id'],
//                'nick' => $nick,
//                'word' => $v['word'],
//                'addtime' => $v['addtime'],
//            ];
//        }
//        return array('code' => 0, 'msg' => 'success', 'data' => $arys, 'total' => $total);
//    }
}